<template>
  <view>
    <u-tabs
      ref="tabs"
      :list="list"
      :is-scroll="false"
      :current="current"
      @change="change"
      bar-height="6"
      bar-width="50"
      active-color="#1D2129"
      inactive-color="#767676"
      :bar-style="{
        backgroundColor: '#F14141'
      }"
    ></u-tabs>
    <view v-if="current == 0" class="back-box">
      <u-form :model="form" ref="uForm" border-bottom>
        <u-form-item required label="充值金额" prop="name" label-width="200">
          <u-input
            type="digit"
            input-align="right"
            placeholder="请输入充值金额"
            :maxlength="12"
            v-model="form.rechargePrice"
          />
        </u-form-item>
      </u-form>
      <view class="tips">充值后，当前金额可用于在当前小程序中进行消费</view>

      <button
        class="u-reset-button money-button"
        hover-class="co-primary-button--hover"
        @click="submit"
      >
        提交
      </button>
    </view>
    <view v-if="current == 1" class="back-box">
      <view class="fund-wrap">
        <view class="fund-title">充值记录</view>
        <view class="fund-day-section" v-for="item in dataList" :key="item.oid">
          <view class="record-content">
            <view class="record-list am-flex-rc-between">
              <view class="record-list-order-info">
                <view class="record-list__order-no am-flex-row-center">
                  <text style="white-space: nowrap"
                    >{{ formatLabelName(item.businessType) }}:</text
                  >
                  <text class="am-text-eill">{{ item.oid }}</text>
                </view>
              </view>
              <view class="record-list-amount">
                <text style="color: #ff6f3c"></text> 充值
                <text
                  class="am-text-eill record-list-amount-num"
                  :style="{ color: '#ffa30b' }"
                >
                  +￥{{ item.price }}
                </text>
              </view>
            </view>
            <view style="float: right"
              ><view class="fund-day-title">{{
                item.payType == 'weChat' ? '微信支付' : '线下支付'
              }}</view></view
            >

            <view class="fund-day-title am-flex-row-center">{{
              $timestampToTime(item.payTime)
            }}</view>
          </view>
        </view>
      </view>
      <co-load-more :type="loadingType"
        ><co-empty slot="empty" model="data" paddingTop="80rpx"></co-empty
      ></co-load-more>
    </view>
  </view>
</template>

<script>
import { accountRecharge, payMoney, payRecord } from '@/api/capital'
// 不允许请求的type
const noRequestType = [1, 2, 3]
const cacheTime = 5 * 60 * 1000 // 缓存数据的时间，单位ms; 5分钟
export default {
  options: { styleIsolation: 'shared' },
  data() {
    return {
      form: {
        rechargePrice: ''
      },
      current: 0,
      dataList: [],
      loadingType: 999,
      oid: '',
      list: [
        {
          name: '账户充值'
        },
        {
          name: '充值记录'
        }
      ]
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo
    }
  },
  onReachBottom() {
    this.getOrderList()
  },
  onPullDownRefresh() {
    this.getInit()
  },
  components: {},
  onLoad(option) {
    this.getInit()
    this.current = option.active || 0
  },

  methods: {
    formatLabelName() {
      return '流水号'
    },
    getInit() {
      this.pageNum = 1
      this.loadingType = 999
      this.dataList = []
      this.getOrderList()
    },
    // 充值
    submit() {
      if (!this.form.rechargePrice) {
        uni.showToast({
          icon: 'none',
          title: '请输入充值金额!'
        })
        return
      }
      accountRecharge({ price: this.form.rechargePrice }).then((res) => {
        console.log(res.data.data.oid, '-=-=-=-=')
        this.oid = res.data.data.oid
        if (this.$store.getters.getOpenId) {
          this.weixinPay()
        } else {
          this.getWeixinInfo()
        }
      })
    },
    // 获取微信用户openId
    getWeixinInfo() {
      let _this = this
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      uni.login({
        provider: 'weixin',
        onlyAuthorize: true,
        success: function (loginRes) {
          console.log(JSON.stringify(loginRes))
          apiGetOpenId({ code: loginRes.code })
            .then((res) => {
              console.log(res)
              let { code, data, msg } = res.data
              if (code == 200) {
                // 获取成功
                _this.$store.commit('SET_OPEN_ID', data.openid)
                _this.weixinPay()
              } else {
                _this.$am_toast.warning(msg)
              }
            })
            .catch((err) => {
              console.log(err)
              uni.hideLoading()
              _this.$am_toast.warning('支付失败！')
              // this.$emit('payFail', {
              //   type: 'pay_error',
              //   orderIds: this.orderIdArr
              // })
            })
        },
        fail: function (err) {
          uni.hideLoading()
          _this.$am_toast.warning('支付失败！')
          // this.$emit('payFail', {
          //   type: 'pay_error',
          //   orderIds: this.orderIdArr
          // })
        }
      })
    },
    // 微信支付
    weixinPay() {
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      uni.getProvider({
        service: 'payment',
        success: (reson) => {
          payMoney({ oid: this.oid })
            .then((res) => {
              console.log(res, 'resres')
              let { code, data, msg } = res.data
              uni.hideLoading()
              if (code == 200) {
                uni.requestPayment({
                  provider: reson.provider[0],
                  timeStamp: data.timeStamp,
                  nonceStr: data.nonceStr,
                  package: data.package,
                  signType: data.signType,
                  paySign: data.paySign,
                  success: (payRes) => {
                    console.log(payRes)
                    // this.$emit('paySuccess')
                    // this.$am_toast.success('支付成功！')
                    uni.redirectTo({
                      url: '/pages/mine/recharge-result'
                    })
                  },
                  fail: (payErr) => {
                    console.log(
                      payErr,
                      'payErrpayErrpayErrpayErrpayErrpayErrpayErrpayErr'
                    )
                    this.$am_toast.warning('支付失败！')
                    // this.$emit('payFail', {
                    //   type: 'pay_error',
                    //   orderIds: this.orderIdArr
                    // })
                  }
                })
              } else {
                this.$am_toast.warning(msg)
                // this.$emit('payFail', {
                //   type: 'pay_error',
                //   orderIds: this.orderIdArr
                // })
              }
            })
            .catch((err) => {
              console.log(err, 'errerrerrerrerrerr')
              uni.hideLoading()
              this.$am_toast.warning('支付失败！支付失败！')
              // this.$emit('payFail', {
              //   type: 'pay_error',
              //   orderIds: this.orderIdArr,
              //   scene: this.scene
              // })
              // this.showPayment = true
            })
        }
      })
    },
    change(index) {
      this.current = index
    },
    getOrderList() {
      if (noRequestType.includes(this.loadingType)) {
        return
      }
      this.loadingType = 999
      console.log('调用获取数据')
      payRecord()
        //   {
        //   pageNum: this.pageNum,
        //   pageSize: 10
        // }
        .then(({ data }) => {
          if (data.state === 'OK') {
            this.dataList = data.data
            this.loadingType = 3
            // if (this.pageNum === 1 && this.dataList.length === 0) {
            //   this.loadingType = 1
            // } else if (data.data.totalPage === this.pageNum) {
            //   this.loadingType = 3
            // } else {
            //   this.loadingType = 999
            //   this.pageNum++
            // }
          }
          uni.stopPullDownRefresh()
        })
        .catch((err) => {
          console.log(err)
          this.loadingType = 999
          this.$am_toast.warning('查询失败，请重新尝试！')
          uni.stopPullDownRefresh()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.back-box {
  margin: 24rpx;
  padding: 32rpx;
  background: #fff;
  .back-price {
    font-weight: 400;
    font-size: 30rpx;
    color: #1d2129;
  }
  // .back-num {
  //   font-size: 32rpx;
  //   color: #f14141;
  //   line-height: 44rpx;
  // }
  .tips {
    margin-top: 15rpx;
    font-size: 22rpx;
    color: #86909c;
    line-height: 40rpx;
  }
}
::v-deep u-form-item {
  font-size: 30rpx;
  color: #1d2129;
}
.money-button {
  margin-top: 300rpx;
  height: 80rpx;
  background: linear-gradient(323deg, #ff4564 0%, #f14141 14%, #fc843b 100%);
  border-radius: 200rpx 200rpx 200rpx 200rpx;
  font-size: 36rpx;
  color: #ffffff;
  line-height: 80rpx;
}
.fund-wrap {
  margin-bottom: 0;
  background: #fff;
}
.fund-day-section {
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 20rpx;
}
.fund-day-title {
  font-size: 24rpx;
  color: #86909c;
  line-height: 50rpx;
}

.record-list {
  position: relative;
  height: 90rpx;
  // border-top: 1px solid #e8e8e8;
}
.record-list-order-info {
  width: 410rpx;
  flex-shrink: 0;
}
.record-list__order-no {
  font-size: 30rpx;
  color: #1d2129;
  line-height: 42rpx;
}
.record-list__supplier-wrap {
  margin-top: 11rpx;
}
.record-list__supplier-name {
  font-size: 28rpx;
  color: #8b8b8d;
}
.record-list-amount {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 1;
  width: 0;
}
.record-list-amount-num {
  font-size: 32rpx;
  color: #f14141;
  line-height: 44rpx;
}
.refund-tag {
  width: 60rpx;
  height: 30rpx;
  font-size: 22rpx;
  color: #ff4d4f;
  background: #fff1f0;
  border-radius: 4rpx;
}
.img {
  width: 58rpx;
  height: 49rpx;
  position: absolute;
  right: 0;
  top: 0;
}
.fund-title {
  margin-bottom: 30rpx;
  font-weight: 600;
  font-size: 30rpx;
  color: #1d2129;
  line-height: 34rpx;
}
</style>
